import pysam
import math
import sys

def main():
    bam_file = sys.argv[1]
    samfile = pysam.AlignmentFile(bam_file, "rb")
    chromosomes = samfile.references
    chrom_data = {chrom: {"sum_len": 0, "sum_len_sq": 0, "sum_mapq": 0, "sum_mapq_sq": 0, "count": 0} for chrom in chromosomes}
    
    for read in samfile.fetch():
        if not (read.is_secondary or read.is_supplementary):
            chrom = samfile.get_reference_name(read.reference_id)
            length = read.query_length
            mapq = read.mapping_quality
            chrom_data[chrom]["sum_len"] += length
            chrom_data[chrom]["sum_len_sq"] += length ** 2
            chrom_data[chrom]["sum_mapq"] += mapq
            chrom_data[chrom]["sum_mapq_sq"] += mapq ** 2
            chrom_data[chrom]["count"] += 1
    
    for chrom in chromosomes:
        data = chrom_data[chrom]
        count = data["count"]
        print(f"染色体: {chrom}")
        print(f"  主对齐读数: {count}")
        if count > 0:
            mean_length = data["sum_len"] / count
            std_dev_length = math.sqrt(max(0, (data["sum_len_sq"] / count) - mean_length ** 2))
            mean_mapq = data["sum_mapq"] / count
            std_dev_mapq = math.sqrt(max(0, (data["sum_mapq_sq"] / count) - mean_mapq ** 2))
            print(f"  序列长度均值: {mean_length:.2f}, 标准差: {std_dev_length:.2f}")
            print(f"  MAPQ均值: {mean_mapq:.2f}, 标准差: {std_dev_mapq:.2f}")
        else:
            print("  无主对齐读数据")
        print()
    
    samfile.close()

if __name__ == "__main__":
    main()